package com.example.utils;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;

public class EmailSender {
    private final String host = "smtp.qq.com"; // 邮箱服务器主机名
    private final String username = "1937180958@qq.com"; // 邮箱用户名
    private final String password = "ahvcpjldlsydcgjh"; // 邮箱
    private final String from = "1937180958@qq.com"; // 发件人邮箱地址
    private final String to; // 收件人邮箱地址
    private final String subject = "验证码"; // 邮件主题
    private final String code; // 验证码

    public EmailSender(String to, String code) {
        this.to = to;
        this.code = code;
    }

    public void send() {
        Properties props = new Properties();
        props.setProperty("mail.transport.protocol", "smtp");
        props.setProperty("mail.smtp.host", host);
        props.setProperty("mail.smtp.auth", "true");
        props.setProperty("mail.smtp.ssl.enable", "true");

        Session session = Session.getInstance(props, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject(subject);
            message.setContent("验证码为：" + code, "text/html;charset=UTF-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }
}
